<?php


class sfWidgetUserNameExists extends sfWidgetFormInput
{

    protected function configure($options = array(), $attributes = array())
    {
        sfContext::getInstance()->getConfiguration()->loadHelpers('Url');
        sfContext::getInstance()->getResponse()->addStylesheet('/sfCustomWidgetsPlugin/css/sfWidgetUserNameExists.css','last');

        $this->addOption( 'model'    , 'sfGuardUser' );
        $this->addOption( 'column'   , null );
        $this->addOption( 'ajax_url' , '@custom_widgets_check_user_name_unique_ajax' );
        $this->addOption( 'culture'  , sfContext::getInstance()->getUser()->getCulture() );
        
        parent::configure( $options , $attributes );
    }
    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        $column = $this->getOption('column'  );
        $column = $column ? $column : $name;
        if(strpos($column , '[')){
            $exp = explode('[',$column);
            $column = substr($exp[1] , 0 , strlen($exp[1])-1 );
        }
        //die($column);
        $culture = $this->getOption('culture');
        $model = $this->getOption('model');
        $url = url_for( $this->getOption('ajax_url') );
        $id = $this->generateId($name);
        $script = <<<EOF
<script type="text/javascript">
     jQuery(function($){
        $('#{$id}').change(function(){
            \$field = $('#{$id}');
            \$loading_div = \$field.next('div.uniqe_pl');
            $.ajax({
                  url : "{$url}"
                , data :  { model: "{$model}", value: \$field.val() , column : "{$column}" }
                , success : function(data){
                    \$loading_div.html(data).removeClass('loading');
                }
                , beforeSend:function(){
                   \$loading_div.html('').addClass('loading');
                }
            });//ajax
        });//bind
    });//load
</script>
EOF;

        $html = "<div class='uniqe_pl {$culture}'></div>";
        
        return parent::render($name , $value , $attributes , $errors).$html.$script;
    }


    public function getStylesheets()
    {
        return array();
    }

    public function getJavaScripts()
    {
        return array();
    }
}
